<template>
  <div>
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
              <a-form-item label="实例名称">
                <a-select
                  v-model="queryParam.instanceId"
                  :allowClear="true"
                  :getPopupContainer="(node) => node.parentNode"
                  mode="combobox"
                  option-label-prop="label"
                  placeholder="请输入实例名称"
                >
                  <a-select-option v-for="instance in instanceOptions" :key="instance.id" :label="instance.name">
                    {{ instance.name }}({{ instance.id }})
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <span class="table-page-search-submitButtons" style="float: left;overflow: hidden;">
              <a-button icon="search" type="primary" @click="searchQuery">查询</a-button>
              <a-button icon="reload" style="margin-left: 8px" type="primary" @click="searchReset">重置</a-button>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button icon="plus" type="primary" @click="handleAdd">新增</a-button>
        <a-button icon="download" type="primary" @click="handleExportXls('设备实例')">导出</a-button>
        <a-upload :action="importExcelUrl" :headers="tokenHeader" :multiple="false" :showUploadList="false" name="file" @change="handleImportExcel">
          <a-button icon="import" type="primary">导入</a-button>
        </a-upload>
        <a-button icon="reload" type="" @click="refreshCache()">刷新缓存</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="batchDel">
              <a-icon type="delete" />
              删除
            </a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <!-- table区域-begin -->
      <div>
        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
          <a style="margin-left: 24px" @click="onClearSelected">清空</a>
        </div>

        <a-table
          :columns="columns"
          :dataSource="dataSource"
          :expandedRowKeys="expandedRowKeys"
          :loading="loading"
          :pagination="false"
          :rowSelection="{ fixed: true, selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          size="middle"
          @expandedRowsChange="handleExpandedRowsChange"
        >
          <template slot="stateSlots" slot-scope="text, record">
            <a-icon
              :style="{'color':record.state===1?'green':'red'}"
              :type="record.state===1?'check-circle':'close-circle'"
              theme="filled" />
            {{ record.stateText }}
          </template>
          <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record.id)">查看</a>
          <a-divider type="vertical"/>
          <template v-if="record.state===0">
            <a @click="handleEdit(record.id)">编辑</a>
            <a-divider type="vertical"/>
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
              <a>删除</a>
            </a-popconfirm>
            <a-divider type="vertical"/>
          </template>
          <a-popconfirm @confirm="setStatus(record)">
            <p slot="title">确定执行{{ record.state === 0 ? '启动' : '停止' }}操作吗?</p>
            <a>{{ record.state === 0 ? '启动' : '停止' }}</a>
          </a-popconfirm>
        </span>
        </a-table>
      </div>
      <DeviceAlarmConfigModal ref="modalForm" @ok="modalFormOk"></DeviceAlarmConfigModal>
    </a-card>
  </div>
</template>

<script>
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {getAction} from '@api/manage'
import DeviceAlarmConfigModal from './AlarmConfigModal.vue'
import JTreeSelect from '@/components/jeecg/JTreeSelect'

export default {
  name: 'DeviceAlarmConfigList',
  mixins: [JeecgListMixin],
  components: {
    DeviceAlarmConfigModal, JTreeSelect
  },
  data() {
    return {
      description: '设备实例管理页面',
      timer: null,
      modelSelect: '',
      instanceOptions: [],
      modelOptions: [],
      stateCount: {},
      loading: false,
      // 展开的行，受控属性
      expandedRowKeys: [],
      // 表头
      columns: [
        {
          title: '告警名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '实例名称',
          dataIndex: 'instanceName',
          key: 'instanceName'
        },
        {
          title: '触发方式',
          dataIndex: 'triggerMethodText',
          key: 'triggerMethod'
        },
        {
          title: '创建日期',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '状态',
          dataIndex: 'stateText',
          scopedSlots: { customRender: 'stateSlots' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        listModel: '/device/model/listAll',
        listInstance: '/device/instance/listAll',
        list: '/alarm/config/list',
        delete: '/alarm/config/delete',
        deleteBatch: '/alarm/config/deleteBatch',
        exportXlsUrl: '/alarm/config/exportXls',
        importExcelUrl: '/alarm/config/importExcel',
        refreshCache: '/alarm/config/refreshCache'
      },
      dictOptions: {}
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  mounted() {
    this.loadInstance()
  },
  methods: {
    refreshCache() {
      let that = this
      getAction(this.url.refreshCache, {}).then(res => {
        if (res.success) {
          that.$message.success('刷新缓存成功！')
        }
      })
    },

    getStateCount(value) {
      let scope = this
      console.log(value)
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        scope.dataSource = []
        getAction(this.url.list, { modelBy: value }).then(res => {
          if (res.success) {
            scope.dataSource = res.result
            scope.stateCount = JSON.parse(res.message)
          }
        })
      }, 300)
    },
    loadInstance() {
      getAction(this.url.listInstance, {}).then(res => {
        if (res.success) {
          this.instanceOptions = res.result
        }
      })
    },
    loadData() {
      let scope = this
      this.dataSource = []
      getAction(this.url.list, {}).then(res => {
        if (res.success) {
          scope.dataSource = res.result
        }
      })
    },
    handleDetail(configId) {
      this.$refs.modalForm.title = '告警配置详情'
      this.$refs.modalForm.detail(configId)
    },
    handleAdd() {
      this.$refs.modalForm.title = '添加设备告警配置'
      this.$refs.modalForm.instanceIdDisable = false
      this.$refs.modalForm.add()
    },
    handleEdit(configId) {
      this.$refs.modalForm.title = '编辑告警配置'
      this.$refs.modalForm.instanceIdDisable = false
      this.$refs.modalForm.edit(configId)
    },
    setStatus(record) {
      let scope = this
      getAction(`alarm/config/setState/${record.id}/${record.state === 1 ? 0 : 1}`).then(data => {
        if (data.success) {
          scope.$message.success(data.message)
          scope.loadData()
        } else {
          scope.$message.warning(data.message)
        }
      })
    },
    initDictConfig() {
    },
    handleExpandedRowsChange(expandedRows) {
      this.expandedRowKeys = expandedRows
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>